<script setup>
import { ref, watch, computed, watchEffect } from 'vue';
import { postService } from "@/services/PostService.js";
import CommentSection from "../Comment/CommentSection.vue";
import DOMPurify from 'dompurify';
import { userManager } from "@/utils/user.js";
import { ElMessage, ElDialog, ElScrollbar } from "element-plus";
import { userServie } from "@/services/user_service.js";

const props = defineProps({
  article: { type: Object, default: null }
});
const emits = defineEmits(['close','comment-added']);

const comments = ref([]);
const isLoadingComments = ref(false);
const username = ref('');

watchEffect(async () => {
  if (props.article && props.article.authorId) {
    try {
      const user = await userServie.getUserById(props.article.authorId);
      username.value = user.username || '未知作者';
    } catch (error) {
      console.error("获取作者用户名失败:", error);
      username.value = '未知作者';
    }
  }
});

const fetchComments = async () => {
  if (!props.article) return;
  isLoadingComments.value = true;
  try {
    comments.value = await postService.getCommentsByPostId(props.article.id);
  } catch (error) {
    console.error("加载评论失败:", error);
  } finally {
    isLoadingComments.value = false;
  }
};

watch(() => props.article, (newArticle) => {
  if (newArticle) fetchComments(); else comments.value = [];
}, { immediate: true });

const handleAddNewComment = async (commentContent) => {
  try {
    const commentData = { contenter: userManager.getUserId(), postId: props.article.id, content: commentContent };
    await postService.createComment(commentData);
    await fetchComments();
    emits('comment-added');
  } catch (error) {
    ElMessage.error('评论失败，请稍后重试');
  }
};

const sanitizedContent = computed(() => {
  return props.article && props.article.content ? DOMPurify.sanitize(props.article.content) : '';
});
const formatDate = (dateValue) => dateValue ? new Date(dateValue).toLocaleString() : '';
</script>

<template>
  <el-dialog
      :model-value="!!article"
      @close="$emit('close')"
      :title="article ? article.title : ''"
      width="60%"
      top="5vh"
      class="article-dialog"
  >
    <div v-if="article">
      <div class="article-meta">
        <span>作者: {{ username }}</span>
        <span>发布于: {{ formatDate(article.createTime) }}</span>
      </div>
      <el-scrollbar max-height="60vh">
        <div class="article-content" v-html="sanitizedContent"></div>
        <div class="comment-section-dialog">
          <h4>评论区</h4>
          <CommentSection :comments="comments" @add-comment="handleAddNewComment" :is-loading="isLoadingComments" />
        </div>
      </el-scrollbar>
    </div>
  </el-dialog>
</template>

<style scoped>
.article-dialog :deep(.el-dialog__header) { padding-right: 50px; border-bottom: 1px solid #e4e7ed; }
.article-dialog :deep(.el-dialog__body) { padding: 0; }
.article-meta { font-size: 13px; color: #86909c; padding: 16px 24px; background-color: #f7f8fa; display: flex; gap: 16px; }
.article-content { padding: 24px; line-height: 1.8; }
:deep(.article-content *) { max-width: 100%; }
.comment-section-dialog { padding: 16px 24px; background-color: #f7f8fa; border-top: 1px solid #e4e7ed; }
.comment-section-dialog h4 { margin: 0 0 16px 0; font-weight: 500; }
</style>